/**
 * 基于网格的用户状态折线图组件
 * 
 * 该文件实现了严格基于网格布局的用户状态折线图可视化
 * - 横轴：时间轴，分为固定的网格区间
 * - 纵轴：5个用户状态，每个状态对应一条水平网格线
 * - 数据点严格对齐到网格交叉点上
 * - 左侧状态标签与网格线完美对齐
 * 
 * 原理：
 * - 使用固定的5x5网格布局
 * - 状态值直接映射到网格行
 * - 时间值按比例映射到网格列
 * - 所有绘制基于网格坐标系统
 */

package com.example.brain_wave.ui.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.brain_wave.ui.components.SharedTimeAxis
import com.example.brain_wave.ui.components.calculateTimeAxisData
import com.example.brain_wave.ui.components.BrainWaveDataPoint
import com.example.brain_wave.ui.components.SlidingChartController

/**
 * 网格化折线图配置
 */
data class LineChartConfig(
    val backgroundColor: Color = Color(0xFF1A1A1A),
    val gridColor: Color = Color(0xFF444444),
    val textColor: Color = Color(0xFFFFFFFF),
    val lineColor: Color = Color(0xFF2196F3),
    val lineWidth: Float = 3f,
    val showGrid: Boolean = true,
    val showLabels: Boolean = true,
    val animationDurationMs: Int = 300,
    val displayTimeWindowSeconds: Int = 30,
    // 网格配置
    val gridRows: Int = 5,  // 5个状态
    val gridCols: Int = 10, // 10个时间区间
    val gridLineWidth: Float = 1f,
    val majorGridLineWidth: Float = 2f
) {
    fun getDisplayTimeWindowMs(): Long = displayTimeWindowSeconds * 1000L
}

/**
 * 网格化用户状态折线图组件
 */
@Composable
fun LineChart(
    dataPoints: List<BrainWaveDataPoint>,
    config: LineChartConfig = LineChartConfig(),
    modifier: Modifier = Modifier,
    slidingController: SlidingChartController? = null
) {
    // 数据处理
    val displayData = if (slidingController != null) {
        val visibleData by slidingController.visibleData.collectAsState()
        LaunchedEffect(dataPoints) {
            slidingController.updateData(dataPoints)
        }
        visibleData
    } else {
        dataPoints.sortedBy { it.timestamp }
    }
    
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(config.backgroundColor)
            .padding(16.dp)
    ) {
        // 图表区域
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
        ) {
            // 左侧状态标签
            GridStateLabels(
                config = config,
                modifier = Modifier
                    .width(80.dp)
                    .fillMaxHeight()
            )
            
            // 主图表区域
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .let { mod ->
                        if (slidingController != null) {
                            mod.pointerInput(Unit) {
                                detectDragGestures { change, dragAmount ->
                                    val deltaMs = (dragAmount.x * -100).toLong()
                                    slidingController.slide(deltaMs)
                                }
                            }
                        } else {
                            mod
                        }
                    }
            ) {
                Canvas(
                    modifier = Modifier.fillMaxSize()
                ) {
                    drawGridChart(displayData, config, size)
                }
            }
        }
        
        // 底部时间轴
        if (config.showLabels && displayData.isNotEmpty()) {
            Spacer(modifier = Modifier.height(8.dp))
            Row(
                modifier = Modifier.fillMaxWidth()
            ) {
                Spacer(modifier = Modifier.width(80.dp)) // 对齐左侧标签宽度
                GridTimeAxis(
                    dataPoints = displayData,
                    config = config,
                    modifier = Modifier.weight(1f)
                )
            }
        }
    }
}

/**
 * 绘制网格化图表
 */
private fun DrawScope.drawGridChart(
    dataPoints: List<BrainWaveDataPoint>,
    config: LineChartConfig,
    canvasSize: androidx.compose.ui.geometry.Size
) {
    val width = canvasSize.width
    val height = canvasSize.height
    
    // 计算网格尺寸
    val cellWidth = width / config.gridCols
    val cellHeight = height / config.gridRows
    
    // 绘制网格
    drawGrid(width, height, cellWidth, cellHeight, config)
    
    if (dataPoints.isEmpty()) return
    
    // 绘制数据
    drawDataOnGrid(dataPoints, width, height, cellWidth, cellHeight, config)
}

/**
 * 绘制网格线
 */
private fun DrawScope.drawGrid(
    width: Float,
    height: Float,
    cellWidth: Float,
    cellHeight: Float,
    config: LineChartConfig
) {
    // 绘制水平网格线（状态分隔线）
    for (i in 0..config.gridRows) {
        val y = i * cellHeight
        val isMainLine = i == 0 || i == config.gridRows
        drawLine(
            color = config.gridColor,
            start = Offset(0f, y),
            end = Offset(width, y),
            strokeWidth = if (isMainLine) config.majorGridLineWidth else config.gridLineWidth
        )
    }
    
    // 绘制垂直网格线（时间分隔线）
    for (i in 0..config.gridCols) {
        val x = i * cellWidth
        val isMainLine = i == 0 || i == config.gridCols
        drawLine(
            color = config.gridColor,
            start = Offset(x, 0f),
            end = Offset(x, height),
            strokeWidth = if (isMainLine) config.majorGridLineWidth else config.gridLineWidth
        )
    }
}

/**
 * 在网格上绘制数据
 */
private fun DrawScope.drawDataOnGrid(
    dataPoints: List<BrainWaveDataPoint>,
    width: Float,
    height: Float,
    cellWidth: Float,
    cellHeight: Float,
    config: LineChartConfig
) {
    if (dataPoints.isEmpty()) return
    
    // 计算时间范围
    val minTime = dataPoints.minOf { it.timestamp }
    val maxTime = dataPoints.maxOf { it.timestamp }
    val timeRange = if (maxTime > minTime) maxTime - minTime else 1L
    
    val path = Path()
    var isFirstPoint = true
    
    dataPoints.forEachIndexed { index, dataPoint ->
        // 计算网格坐标
        val gridCoords = calculateGridPosition(
            dataPoint, minTime, timeRange, width, height, cellWidth, cellHeight, config
        )
        
        val x = gridCoords.first
        val y = gridCoords.second
        
        // 构建路径
        if (isFirstPoint) {
            path.moveTo(x, y)
            isFirstPoint = false
        } else {
            path.lineTo(x, y)
        }
        
        // 绘制数据点
        drawDataPoint(dataPoint, x, y)
    }
    
    // 绘制连线
    drawPath(
        path = path,
        color = Color.White.copy(alpha = 0.9f),
        style = Stroke(
            width = config.lineWidth,
            cap = StrokeCap.Round,
            join = StrokeJoin.Round
        )
    )
}

/**
 * 计算数据点在网格中的精确位置
 */
private fun calculateGridPosition(
    dataPoint: BrainWaveDataPoint,
    minTime: Long,
    timeRange: Long,
    width: Float,
    height: Float,
    cellWidth: Float,
    cellHeight: Float,
    config: LineChartConfig
): Pair<Float, Float> {
    // 状态到网格行的映射（从底部开始计数）
    val stateToRow = when (dataPoint.userState) {
        UserState.DEEP_SLEEP -> 4    // 底部
        UserState.LIGHT_SLEEP -> 3
        UserState.REM_SLEEP -> 2
        UserState.DROWSY -> 1
        UserState.AWAKE -> 0         // 顶部
    }
    
    // Y坐标：状态对应的网格线位置
    val y = (stateToRow + 0.5f) * cellHeight // 0.5f使点位于网格线中心
    
    // X坐标：时间比例映射到宽度
    val timeRatio = if (timeRange > 0) {
        (dataPoint.timestamp - minTime).toFloat() / timeRange
    } else {
        0.5f
    }
    val x = timeRatio * width
    
    return Pair(x, y)
}

/**
 * 绘制单个数据点
 */
private fun DrawScope.drawDataPoint(
    dataPoint: BrainWaveDataPoint,
    x: Float,
    y: Float
) {
    val pointColor = when (dataPoint.userState) {
        UserState.DEEP_SLEEP -> Color(0xFF1976D2)   // 深蓝
        UserState.LIGHT_SLEEP -> Color(0xFFFF9800)  // 橙色
        UserState.REM_SLEEP -> Color(0xFF4CAF50)    // 绿色
        UserState.DROWSY -> Color(0xFFFFC107)       // 黄色
        UserState.AWAKE -> Color(0xFFF44336)        // 红色
    }
    
    // 绘制阴影
    drawCircle(
        color = Color.Black.copy(alpha = 0.3f),
        radius = 8.dp.toPx(),
        center = Offset(x + 1.dp.toPx(), y + 1.dp.toPx())
    )
    
    // 绘制主要数据点
    drawCircle(
        color = pointColor,
        radius = 7.dp.toPx(),
        center = Offset(x, y)
    )
    
    // 绘制白色边框
    drawCircle(
        color = Color.White,
        radius = 7.dp.toPx(),
        center = Offset(x, y),
        style = Stroke(width = 2.dp.toPx())
    )
}

/**
 * 网格化状态标签
 */
@Composable
private fun GridStateLabels(
    config: LineChartConfig,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.padding(end = 8.dp),
        verticalArrangement = Arrangement.SpaceEvenly
    ) {
        // 按照网格顺序排列：从上到下
        val states = listOf(
            UserState.AWAKE,
            UserState.DROWSY,
            UserState.REM_SLEEP,
            UserState.LIGHT_SLEEP,
            UserState.DEEP_SLEEP
        )
        
        states.forEach { state ->
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.End,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            ) {
                Text(
                    text = state.displayName,
                    color = config.textColor,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Medium
                )
                Spacer(modifier = Modifier.width(8.dp))
                Box(
                    modifier = Modifier
                        .size(12.dp)
                        .background(
                            color = when (state) {
                                UserState.DEEP_SLEEP -> Color(0xFF1976D2)
                                UserState.LIGHT_SLEEP -> Color(0xFFFF9800)
                                UserState.REM_SLEEP -> Color(0xFF4CAF50)
                                UserState.DROWSY -> Color(0xFFFFC107)
                                UserState.AWAKE -> Color(0xFFF44336)
                            },
                            shape = androidx.compose.foundation.shape.CircleShape
                        )
                )
            }
        }
    }
}

/**
 * 网格化时间轴
 */
@Composable
private fun GridTimeAxis(
    dataPoints: List<BrainWaveDataPoint>,
    config: LineChartConfig,
    modifier: Modifier = Modifier
) {
    if (dataPoints.isEmpty()) return
    
    val startTime = dataPoints.first().timestamp
    val endTime = dataPoints.last().timestamp
    
    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        // 显示网格列对应的时间点
        for (i in 0..config.gridCols step 2) { // 每隔2列显示一个时间点
            val ratio = i.toFloat() / config.gridCols
            val time = startTime + ((endTime - startTime) * ratio).toLong()
            val formattedTime = formatTimeToHMS(time)
            Text(
                text = formattedTime,
                color = config.textColor,
                fontSize = 10.sp
            )
        }
    }
}

/**
 * 格式化时间为 HH:mm:ss 格式
 */
private fun formatTimeToHMS(timestamp: Long): String {
    val calendar = java.util.Calendar.getInstance()
    calendar.timeInMillis = timestamp
    
    val hour = calendar.get(java.util.Calendar.HOUR_OF_DAY)
    val minute = calendar.get(java.util.Calendar.MINUTE)
    val second = calendar.get(java.util.Calendar.SECOND)
    
    return String.format("%02d:%02d:%02d", hour, minute, second)
}